import type { TBody, TParams } from '@/types';
import { createConfig, getQueryParams, handleReqMiddleware } from '@/lib/api';
import type { ISectionGroup, ISectionGroupStatistics } from '@/interfaces';

export const querySectionGroupStatistics = (
  params?: TParams
): Promise<Response | ISectionGroupStatistics> => {
  const config = createConfig(params);
  return fetch(config.baseURL + '/forum/sectionGroups/statistics', config).then(
    handleReqMiddleware
  );
};

export const queryAllSectionGroup = (
  params?: TParams
): Promise<Response | ISectionGroup[]> => {
  const config = createConfig(params);
  return fetch(
    config.baseURL + `/forum/sectionGroups?${getQueryParams(config)}`,
    config
  ).then(handleReqMiddleware);
};

export const querySectionGroup = (
  params?: TParams
): Promise<Response | ISectionGroup> => {
  const config = createConfig(params);
  return fetch(
    config.baseURL + `/forum/sectionGroups/${config.id}`,
    config
  ).then(handleReqMiddleware);
};

export const createSectionGroup = (
  params: TBody<{
    name: string;
  }>
): Promise<Response | void> => {
  const config = createConfig(params, { method: 'POST' });
  return fetch(config.baseURL + '/forum/sectionGroups', config).then(
    handleReqMiddleware
  );
};

export const updateSectionGroup = (
  params: TBody<{
    name?: string;
    sort?: number;
  }>
): Promise<Response | void> => {
  const config = createConfig(params, { method: 'PUT' });
  return fetch(
    config.baseURL + `/forum/sectionGroups/${config.id}`,
    config
  ).then(handleReqMiddleware);
};

export const createSectionGroupSection = (
  params: TBody<{
    sectionId: string;
  }>
): Promise<Response | void> => {
  const config = createConfig(params, { method: 'POST' });
  return fetch(
    config.baseURL +
      `/forum/sectionGroups/${config.id}/sections/${params.data!.sectionId}`,
    config
  ).then(handleReqMiddleware);
};

export const removeSectionGroupSection = (
  params: TBody<{
    sectionId: string;
  }>
): Promise<Response | void> => {
  const config = createConfig(params, { method: 'DELETE' });
  return fetch(
    config.baseURL +
      `/forum/sectionGroups/${config.id}/sections/${params.data!.sectionId}`,
    config
  ).then(handleReqMiddleware);
};
